package com.friday.util;

import org.springframework.util.ClassUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public final class UploadImg {

    public static String upload(MultipartFile avatar){
        //保存时的文件名(通过加入当前时间戳来防止文件名称相同)
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        String dateName = df.format(calendar.getTime())+avatar.getOriginalFilename();

        //获取项目static的地址
        String staticPath = System.getProperty("user.dir")+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static";

        //图片相对路径
        String url_path =  File.separator + "photo" + File.separator + dateName;

        //图片保存路径(绝对路径)
        String savePath = staticPath  + url_path;
        savePath = "D:\\friday\\photo\\" + dateName;

        //savePath = "/root/jarPackage/photo/" + dateName;

        //生成文件
        File newFile = new File(savePath);

        //MultipartFile的方法直接写文件
        try {
            //存储图片
            avatar.transferTo(newFile);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return url_path;
    }

    public static void delete(String url_path){
        //获取项目static的地址
        String staticPath = System.getProperty("user.dir")+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static";
        //图片保存路径(绝对路径)
        String savePath = "D:\\friday"  + url_path;
        //获取文件
        File file=new File(savePath);
        if(file.exists() && !file.getName().equals("defaultAvatar.png"))
        {
            file.delete();
        }

    }



}
